package cn.smvc.task.common.service;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.smvc.common.Constant;
import cn.smvc.common.cache.CacheManager;
import cn.smvc.task.entity.TTimedTask;
import cn.smvc.task.service.TTimedTaskService;

public class MainService extends Thread{
	
	private ServletContext servletContext;

	@Autowired
	private TTimedTaskService tTimedTaskService;
	
	public MainService(ServletContext servletContext) {
		super();
		this.servletContext = servletContext;
		WebApplicationContextUtils.getWebApplicationContext(servletContext)
				.getAutowireCapableBeanFactory().autowireBean(this);
	}
	
	
	@Override
	public void run() {
		try {
			//启动将所有任务都置成空闲状态
			tTimedTaskService.updateAllRunFlag("F");
			//查询所有的任务
			List<TTimedTask> list = tTimedTaskService.findAll();
			for(TTimedTask task : list) {
				//将任务逐个写入缓存中
				CacheManager.put(Constant.CACHE_TASK_PREFIX + task.getId(), task);
			}
			
			
			while (true) {
				
//				System.out.println("MainService... ... ");
				//从缓存中获取所有的任务缓存信息
				List<Object> taskCacheList = CacheManager.getCacheList(Constant.CACHE_TASK_PREFIX);
				for(Object obj : taskCacheList) {
					TTimedTask task = (TTimedTask) obj;
					if("T".equals(task.getSwithFlag())) {
						if("F".equals(task.getRunFlag())) {
							task.setRunFlag("T");
							tTimedTaskService.updateRunFlag(task.getId(), "T");//保存数据库
							TimedTaskService TimedTaskService = new TimedTaskService(task, servletContext);
							TimedTaskService.start();
						}
					}
				}
				// 巡检间隔
				try {
					sleep(Constant.MAIN_SLEEP_TIME);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}


}
